<template>
  <div
    v-loading="true"
    element-loading-text="登录中..."
    element-loading-background="rgba(0, 0, 0, 0.7)"
    class="login-container"
  />
</template>

<script>
import { getToken } from '@/api/auth'

export default {
  name: 'SSOLogin',
  data() {
    return {
      code: '',
      userData: {
        token: '',
        accessToken: '',
        id: ''
      }
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.code = route.query && route.query.code
      },
      immediate: true
    }
  },
  mounted() {
    this.code = this.$route.query.code
    if (this.code && !this._.isEmpty(this.code)) {
      this.getToken()
    } else {
      this.backLogin()
    }
  },
  methods: {
    getToken() {
      getToken({
        code: this.code
      }).then(response => {
        console.log('getToken', response)
        const resData = response.data
        if (response.rtncode === 200 &&
          !this._.isEmpty(resData.accessToken) &&
          !this._.isEmpty(resData.token)
        ) {
          this.userData.accessToken = resData.accessToken
          this.userData.token = resData.token
          this.userData.id = resData.adminUserId

          this.$store.dispatch('user/ssoLogin', this.userData).then(() => {
            this.$router.push('/')
          }).catch(error => {
            console.log(error)
            this.backLogin()
          })
        } else {
          console.log('no accessToken')
          this.backLogin()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    backLogin() {
      // this.$router.push('/login')
      this.$router.push('/')
    }
  }
}
</script>

<style lang="scss">
.login-container {
  min-height: 100%;
  width: 100%;
  overflow: hidden;
}
</style>
